package com.example.graphic.handler;

import com.example.graphic.model.vo.CommonResponse;
import com.example.graphic.model.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 处理参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<Object> handleIllegalArgumentException(IllegalArgumentException e) {
        return Result.error(400, "参数错误: " + e.getMessage());
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<Object> handleRuntimeException(RuntimeException e) {
        System.err.println("运行时异常: " + e.getMessage());
        e.printStackTrace();
        return Result.error("系统异常，请稍后重试");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        System.err.println("系统异常: " + e.getMessage());
        e.printStackTrace();
        return Result.error("系统异常，请稍后重试");
    }
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<CommonResponse<Void>> handleBusinessException(BusinessException e) {

        CommonResponse<Void> response = CommonResponse.error(e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理第三方API调用异常
     */
    @ExceptionHandler(AIApiException.class)
    public ResponseEntity<CommonResponse<Void>> handleAIApiException(AIApiException e) {

        CommonResponse<Void> response = CommonResponse.error("AI服务调用失败: " + e.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }
}
